package com.buding.fx.validators;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.validation.base.ValidatorBase;
import javafx.scene.control.Button;

import java.util.regex.Pattern;

/**
 * java字段标识校验
 */
public class JavaFieldValidator extends ValidatorBase {
    private int length;
    private static final Pattern FIELD_NAME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]*");


    public JavaFieldValidator(int length){
        this.length = length;
    }

    @Override
    protected void eval() {
        JFXTextField textField = (JFXTextField) srcControl.get();
        String text = textField.getText();
        if (text.isEmpty()){
            setMessage("所输入的字段不能为空");
            hasErrors.set(true);
        }else{
            if (text.length() > length - 1){
                setMessage("所输入的字段长度不合法");
                hasErrors.set(true);
            }else{
                boolean result = FIELD_NAME_PATTERN.matcher(text).matches();
                System.out.println("java field validate result: "+result);
                if (!result){
                    setMessage("输入字段不合法");
                }
                hasErrors.set(!result);
            }
        }
    }
}
